import React, { Component } from 'react';
import { connect } from 'dva';

import { isEqual } from 'lodash';

import { Form } from '@ant-design/compatible';

import {
  Card,
  Col,
  Input,
  InputNumber,
  Row,
} from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1430304_y2xsdrlvrh.js',
});

const { TextArea } = Input;
const { Item } = Form;

interface HardwareProductProps {
  detail?: any;
  forms: any;
  mergeFun: (name: string, value: any) => void;
}

interface HardwareProductState {
  reserve_list: any;
  prev_reserve_list: any;
}

function mapStateToProps(state: any) {
  const {
    franchiseeContractEditor: { detail },
  } = state;

  return {
    detail,
  };
}

@connect(mapStateToProps)

class HardwareProductElem extends Component<HardwareProductProps, HardwareProductState> {
  state = {
    reserve_list: [
      {
        id: 0,
        batch_num: 1,
        time: 0,
        amount: 0,
        remark: '',
      },
    ],
    prev_reserve_list: [],
  };

  static getDerivedStateFromProps(nextProps: HardwareProductProps, preState: HardwareProductState) {
    const { detail: { reserve_list }, mergeFun } = nextProps;

    if (!isEqual(reserve_list, preState.prev_reserve_list) && reserve_list) {
      mergeFun('reserve_list', JSON.stringify(reserve_list));
      return {
        reserve_list,
        prev_reserve_list: reserve_list,
      };
    }

    return null;
  }

  changeForms = (index: any, changeType: string, value: any) => {
    value = typeof (value) === 'object' && value ? value.target.value : value;

    this.change_reserve_list(index, value, changeType);
  }

  change_reserve_list = (index: any, value: any, changeType: any) => {
    const { reserve_list } = this.state;
    const { mergeFun } = this.props;
    const new_reserve_list = reserve_list.map(item => ({ ...item }));

    new_reserve_list[index][changeType] = value;
    this.setState({ reserve_list: new_reserve_list }, () => {
      const { reserve_list: values } = this.state;
      mergeFun('reserve_list', JSON.stringify(values));
    });
  }

  // 添加批次
  handleAddOrder = () => {
    const { reserve_list } = this.state;
    const new_reserve_list = reserve_list.map((item, index) => ({ ...item }));
    const { length } = new_reserve_list;

    new_reserve_list.push({
      id: new_reserve_list[length - 1].id + 1,
      batch_num: 0,
      time: 0,
      amount: 0,
      remark: '',
    });

    this.setState({ reserve_list: new_reserve_list });
  }

  // 删除批次
  handleDeleteOrder = (index: number) => {
    const { reserve_list } = this.state;
    const new_reserve_list = reserve_list.map(item => ({ ...item }));
    const { forms: { resetFields } } = this.props;
    resetFields(['time', 'amount', 'remark']);

    new_reserve_list.splice(index, 1);

    new_reserve_list.map((item, key) => {
      item.batch_num = key + 1;
      return item;
    });

    this.setState({ reserve_list: new_reserve_list });
  }

  render() {
    const { reserve_list = [] } = this.state;
    const { forms: { getFieldDecorator } } = this.props;

    const clos: any[] = reserve_list.map((item: any, index: number) => (
      <Col
        md={10}
        sm={24}
        key={item.id || index}
        style={{
          marginBottom: 20,
          position: 'relative',
          bottom: -10,
        }}
      >
        <div className="dottedBox" style={{ display: 'flex' }}>
          <div style={{ marginRight: 8, width: 56 }}>
            <div className="operLink" onClick={this.handleAddOrder}>
              <MyIcon type="iconjiahao" style={{ margin: '4px 4px 0 0' }} />
              增加
            </div>
            {index >= 1 && (
              <div
                className="operLink"
                style={{ marginTop: 24, color: '#ff4d4f' }}
                onClick={this.handleDeleteOrder.bind(this, index)}
              >
                <MyIcon type="iconjianhao" style={{ margin: '4px 4px 0 0' }} />
                删除
              </div>
            )}
          </div>
          <div className="tableListForm" style={{ flex: 1 }}>
            <span style={{ display: 'block' }} className="marginB12">
              订购批次：第{item.batch_num || index + 1}批
            </span>
            <Item label="　 时间(天)" colon={false}>
              {getFieldDecorator(`time[${index}]`, {
                initialValue: item.time,
                rules: [{ required: true, message: '请输入时间' }],
              })(
                <InputNumber
                  min={0}
                  style={{ width: '90%' }}
                  placeholder="请输入"
                  onChange={this.changeForms.bind(this, index, 'time')}
                />,
              )}
            </Item>
            <Item label="柜体格口数" colon={false}>
              {getFieldDecorator(`amount[${index}]`, {
                initialValue: item.amount,
                rules: [{ required: true, message: '请输入柜体格口数' }],
              })(
                <InputNumber
                  min={0}
                  style={{ width: '90%' }}
                  placeholder="请输入"
                  onChange={this.changeForms.bind(this, index, 'amount')}
                />,
              )}
            </Item>
            <Item
              label="　备注说明"
              required
              colon={false}
              className="marginB0Import"
            >
              {getFieldDecorator(`remark[${index}]`, {
                initialValue: item.remark,
                rules: [{ required: true, message: '请输入备注说明' }],
              })(
                <TextArea
                  style={{ width: '90%' }}
                  placeholder="请输入"
                  id="success"
                  onChange={this.changeForms.bind(this, index, 'remark')}
                />,
              )}
            </Item>
          </div>
        </div>
      </Col>
    ));

    return (
      <Card title="硬件产品交付约定" bordered={false}>
        <Row gutter={12}>
          {clos}
        </Row>
      </Card>
    );
  }
}

export default HardwareProductElem;
